package com.jiubanqingchen.org.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;
import com.jiubanqingchen.framework.base.service.BaseService;
import com.jiubanqingchen.kit.ApplicationKit;
import com.jiubanqingchen.model.models.Attachment;

import java.io.File;
import java.text.DecimalFormat;
import java.util.Date;

/**
 * @author light_dust
 * @since 2021/3/19 15:07
 */
public class UploadService extends BaseService {

    /**
     * (上传文件 路径: 文件上传配置路径 + 当前日期(yyyyMMdd) + 文件名称)
     * @param  uploadFile 上传文件
     * @param  busiId   业务Id
     * @param itemType 业务类型
     * @param   userId 用户id
     * @return Attachment    返回类型
     * @author Light_dust
     * @since 2019年11月4日
     */
    public Attachment uploadFile(UploadFile uploadFile, String busiId, String itemType, String userId) {
        String uploadUrl = ApplicationKit.me().getUploadPath();//文件上传配置路径
        String fileName = uploadFile.getFileName();// 文件上传名称
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1);// 得到文件后缀
        String fileSize = getFileSizeString(uploadFile.getFile());
        // String size=FileTool.getFileSize(sizes);//获取文件大小
        Date now = new Date();
        String folderUrl = "/" + DateUtil.format(now, "yyyy-MM-dd") + "/" + itemType + "/";// 当前文件上传文件夹(日期 +文件上传业务类型)
        createFileOrDirectory(uploadUrl + folderUrl);// 校验上传文件夹是否被创建,未创建则进行创建 置换为hu-tool的方法
        //FileTool.judgeDirExists(new File());
        String newName = DateUtil.format(now, "yyyyMMddHHmmss") + fileName.substring(fileName.lastIndexOf("."));//文件重命名
        uploadFile.getFile().renameTo(new File(uploadUrl + folderUrl + newName));//更改文件储存路径

        Attachment attachment = new Attachment();
        attachment.setBusiId(busiId).setFileName(fileName).setItemType(itemType).setFileExt(extension)
                .setFilePath(folderUrl + newName).setSize(fileSize);
        attachment.setFileId(StrKit.getRandomUUID()).setCreatePerson(userId).setCreateTime(new Date())
                .setMimeType(uploadFile.getContentType()).save();
        return attachment;
    }

    /**
     * 得到文件的大小转换为 kb mb
     *
     * @param file 文件
     */
    String getFileSizeString(File file) {
        long size = FileUtil.size(file);
        if (size <= 0) return "0";
        final String[] units = new String[]{"B", "kB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    void createFileOrDirectory(String path) {
        if (!FileUtil.exist(path)) {
            File file = new File(path);
            file.setWritable(true, false);
            file.mkdirs();
        }
    }
}
